package com.itheima.mp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Db;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IAddressService;
import com.itheima.mp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public void DeductBalance(Long id, Integer money) {
//        查询用户
        User user = getById(id);
//        校验用户状态
        if(user==null|| user.getStatus()== UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常");
        }
//        校验余额是否充足
        if(user.getBalance()<money){
            throw new RuntimeException("用户余额不足");
        }
//        扣减余额
        baseMapper.deductBalance(id,money);
    }

    /**
     * 条件查询
     * @param userQuery
     * @return
     */
    @Override
    public List<User> queryUsers(UserQuery userQuery) {
        List<User> userList = lambdaQuery().like(userQuery.getName() != null, User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .gt(userQuery.getMinBalance() != null, User::getBalance, userQuery.getMinBalance())
                .lt(userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMaxBalance())
                .list();
        return userList;
    }
    @Autowired
    private IAddressService addressService;
    @Override
    public UserVO queryUserAndAddressById(Long id) {
//        查询用户
        User user = getById(id);
        if(user==null||user.getStatus()==UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常");
        }
//        查询地址

//        此处没有Db包，与下面的对比，我的优势是无需创建对象
//        Db.lambdaQuery(Address.class)..eq(Address::getUserId, id).list();

        List<Address> addressList = addressService.lambdaQuery().eq(Address::getUserId, id).list();

        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        if(CollUtil.isNotEmpty(addressList)){
            userVO.setAddresses(BeanUtil.copyToList(addressList, AddressVO.class));
        }

        return userVO;
    }
}
